package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.DetailsActivity;
import com.luoxiang.socialandroid.adapter.FollowAdapter;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.BeforeCallBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.Typehost2Bean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.base.CallParam;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class FollowFragment extends LazyLoadFragment {
    private RecyclerView rc_follow;
    private String token;
    private FollowAdapter adapter;

    private String mUserid;

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    @Override
    protected int setContentView() {
        return R.layout.fragment_follow;
    }

    @Override
    protected void initView() {
        mUserid = MmkvUtil.INSTANCE.decodeString(ACCID);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        rc_follow = findViewById(R.id.rc_follow);

    }

    @Override
    protected void lazyLoad() {

    }

    @Override
    public void onResume() {
        super.onResume();
        getRequest();
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        getTypeHosts(token, EXTRA, 0);
    }

    private void getTypeHosts(String token, String extra, int i) {
        NetUtils2.getInstance().getApiService().getTypeHosts2(token, extra, "3",1,"10")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStr9096", decryptStr);
                            Gson gson = new Gson();
                            Typehost2Bean bean = gson.fromJson(decryptStr, Typehost2Bean.class);

                            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
                            rc_follow.setLayoutManager(linearLayoutManager);
                            if (bean != null) {
                                if (bean.getData() != null) {
                                    if (bean.getData().getHosts() != null && bean.getData().getHosts().size() != 0) {
                                        adapter = new FollowAdapter(bean.getData().getHosts());
                                        rc_follow.setAdapter(adapter);

                                        adapter.setOnAddClickListener(new FollowAdapter.OnAddClickListener() {
                                            @Override
                                            public void onItemClicks(int userid) {
                                                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                                                intent.putExtra("userid", userid);
                                                startActivity(intent);
                                            }
                                        });
                                        adapter.setOnAddClickListenerDs(new FollowAdapter.OnAddClickListenerDs() {
                                            @Override
                                            public void onItemClicksDs(int position, int userid) {
                                                if (bean.getData().getHosts().get(position).getCall() == 0) {
                                                    sayhello(token, EXTRA, userid);
                                                    getTypeHosts(token, EXTRA, 4);
                                                }
                                            }
                                        });
                                        adapter.setOnAddClickListenerSx(new FollowAdapter.OnAddClickListenerSx() {
                                            @Override
                                            public void onItemClicksSx(int userid) {
                                                if (mUserid.equals(String.valueOf(userid))) {
                                                    ToastUtils.showShort(R.string.mi_bunenghezijiliaotian);
                                                } else {
                                                    XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE).withParam(RouterConstant.CHAT_KRY, new UserInfo(userid + "", "aaa", "")).withContext(getActivity()).navigate();
                                                }
                                            }
                                        });
                                        adapter.setOnAddClickListenerShipin(new FollowAdapter.OnAddClickListenerShipin() {
                                            @Override
                                            public void onItemClicksShipin(int userid) {
                                                //点击视频
                                                //跳转视频通话之前做视频通话预检
                                                getimPre(EXTRA, userid + "", token);
                                            }
                                        });
                                    }
                                }
                            }

                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getimPre(String extra, String toUserId, String token) {
        NetUtils.getInstance().getApiService().getimPre(extra, toUserId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        BeforeCallBean bean = gson.fromJson(decryptStr, BeforeCallBean.class);
                        if (bean.getCode() == 0) {
                            //可以发起通话
                            int accId = MmkvUtil.INSTANCE.decodeInt(ACCID);
                            String id = UUID.randomUUID().toString().replace("-","");
                            CallParam param = CallParam.createSingleCallParam(2, accId + "", toUserId + "",null,null,id);
                            CallKitUI.startSingleCall(getContext(), param);
                        } else {
                            ToastUtils.showShort(bean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void sayhello(String token, String extra, int userid) {
        NetUtils2.getInstance().getApiService().sayHello(token, extra, userid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        ToastUtils.showShort(R.string.mi_dazhaohuchenggong);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }
}